package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品(使用工具类接收数据)
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("菜品数据：{}", dishDto);

        //TODO 调用service层中构造的方法
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 停售/启售功能
     */
    @PostMapping("/status/{id}")
    public R<String> listUpdated(@RequestParam List<Long> ids) {
        log.info("修改id为：{}", ids);

        dishService.updateWithSetmeal(ids);

        return R.success("修改成功");
    }

    /**
     * TODO 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //创建分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null, Dish::getName, name);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, lqw);

        // TODO 对象拷贝
        BeanUtils.copyProperties(pageInfo, dishPage, "records");

        // TODO 创建数据集合并进行处理
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((itm) -> {
            //创建一个新的DishDto对象
            DishDto dishDto = new DishDto();
            //拷贝dish对象
            BeanUtils.copyProperties(itm, dishDto);
            //获取分类id
            Long categoryId = itm.getCategoryId();
            //通过分类id获取分类对象
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                dishDto.setCategoryName(byId.getName());
            }

            //返回新dishDto对象
            return dishDto;
        }).collect(Collectors.toList());

        //将处理完的数据放入新的分页构造器中
        dishPage.setRecords(list);


        return R.success(dishPage);
    }

    /**
     * 查找菜品(使用工具类接收数据)
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        log.info("菜品数据：{}", id);

        //TODO 调用service层中构造的方法
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);

        return R.success(byIdWithFlavor);
    }


    /**
     * 修改菜品(使用工具类接收数据)
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("菜品数据：{}", dishDto);

        //TODO 调用service层中构造的方法
        dishService.updateWithFlavor(dishDto);

        return R.success("更新成功");
    }


    /**
     * 删除
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {

        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            if (byId.getStatus() != 1) {
                dishService.removeById(byId);
            } else {
                return R.error("该菜品未停售，不能删除");
            }
        }
        return R.success("删除成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     */
   /* @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //创建查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //查询状态为1（启售）的菜品
        lqw.eq(Dish::getStatus,1);

        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //进行查询
        List<Dish> list = dishService.list(lqw);

        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //创建查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询状态为1（启售）的菜品
        lqw.eq(Dish::getStatus, 1);

        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //进行查询
        List<Dish> list = dishService.list(lqw);
        List<DishDto> listDto = list.stream().map((itm) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(itm, dishDto);

            //根据id搜索分类对象
            Category byId = categoryService.getById(dish.getCategoryId());
            if (byId != null) {
                dishDto.setCategoryName(byId.getName());
            }

            //根据id获取口味对象
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper();
            lqw1.eq(DishFlavor::getDishId, itm.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw1);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());


        return R.success(listDto);
    }


}
